import { userService } from './userService'

export const userAPI = {
    // 登录：存储用户ID，适配后端响应
    async login(credentials) {
        try {
            const { phone, password } = credentials;
            console.log('🔐 发起登录请求:', { phone })

            const response = await userService.login(phone, password)
            console.log('📨 登录响应:', response)

            if (response?.message === '登录成功') {
                console.log('✅ 登录成功，创建本地用户数据');
                // 存储后端返回的ID（核心），无则默认1
                const userData = {
                    id: response.data?.id || 1,
                    phone: phone,
                    role: response.data?.role || 'USER',
                    status: response.data?.status || 1,
                    loginTime: new Date().getTime(),
                    rawLoginTime: new Date().toLocaleString()
                }

                localStorage.setItem('user', JSON.stringify(userData))
                return {
                    success: true,
                    message: '登录成功',
                    data: userData
                }
            } else {
                console.error('❌ 登录失败（后端返回）:', response?.message);
                return {
                    success: false,
                    message: response?.message || '登录失败，请检查账号密码'
                }
            }

        } catch (error) {
            console.error('❌ 登录异常:', error);

            let errorMsg = '登录失败，请重试';
            if (error.response) {
                const { status } = error.response;
                if (status === 401) errorMsg = '账号或密码错误';
                else if (status === 403) errorMsg = '权限不足';
                else errorMsg = `登录失败（状态码：${status}）`;
            } else if (error.message.includes('Network Error')) errorMsg = '无法连接服务器';
            else if (error.message.includes('timeout')) errorMsg = '请求超时';

            return { success: false, message: errorMsg };
        }
    },

    // 登出：清理本地存储
    async logout() {
        try {
            const response = await userService.logout();
            localStorage.removeItem('user');
            console.log('✅ 登出成功');
            return {
                success: true,
                message: response?.message || '登出成功'
            };
        } catch (error) {
            console.error('❌ 登出异常:', error);
            localStorage.removeItem('user');
            return {
                success: false,
                message: '登出请求失败，已清除本地信息'
            };
        }
    },

    // 注册：存储用户ID
    async register(userData) {
        try {
            const response = await userService.register(userData);
            if (response.success && response.data) {
                const user = {
                    id: response.data?.id || 1, // 存储ID
                    ...response.data,
                    loginTime: new Date().getTime(),
                    rawLoginTime: new Date().toLocaleString()
                };
                localStorage.setItem('user', JSON.stringify(user));
            }
            return {
                success: response.success ?? true,
                message: response.message || '注册成功',
                data: response.data
            };
        } catch (error) {
            console.error('❌ 注册错误:', error);
            return {
                success: false,
                message: error.response?.data?.message || '注册失败'
            };
        }
    },

    // 修改密码
    async alterPassword(phone, newPassword) {
        try {
            const response = await userService.alterPassword(phone, newPassword);
            return {
                success: response.success ?? true,
                message: response.message || '密码修改成功'
            };
        } catch (error) {
            console.error('❌ 修改密码错误:', error);
            return {
                success: false,
                message: error.response?.data?.message || '密码修改失败'
            };
        }
    },

    // 注销账户
    async deleteUser(phone) {
        try {
            const response = await userService.deleteUser(phone);
            if (response.success) localStorage.removeItem('user');
            return {
                success: response.success ?? true,
                message: response.message || '账户注销成功'
            };
        } catch (error) {
            console.error('❌ 注销账户错误:', error);
            return {
                success: false,
                message: error.response?.data?.message || '账户注销失败'
            };
        }
    },

    // 管理员修改用户状态
    async alterStatus(phone) {
        try {
            const response = await userService.alterStatus(phone);
            return {
                success: response.success ?? true,
                message: response.message || '状态修改成功'
            };
        } catch (error) {
            console.error('❌ 修改状态错误:', error);
            return {
                success: false,
                message: error.response?.data?.message || '状态修改失败'
            };
        }
    },

    // 获取用户列表（仅管理员）
    async getUsersList() {
        try {
            const response = await userService.getUsersList();
            return {
                success: response.success ?? true,
                data: response.data || [],
                message: response.message || '获取用户列表成功'
            };
        } catch (error) {
            console.error('❌ 获取用户列表错误:', error);
            return {
                success: false,
                data: [],
                message: '非管理员无权限或获取失败'
            };
        }
    },

    // 检查认证状态
    async checkAuthStatus() {
        try {
            const currentUser = this.getCurrentUser();
            if (!currentUser?.phone) return { isAuthenticated: false };

            if (this.hasRole('ROLE_ADMIN')) {
                const listResult = await userService.getUsersList();
                const isAuthenticated = Array.isArray(listResult.data);
                return { isAuthenticated, user: currentUser };
            } else {
                return { isAuthenticated: true, user: currentUser };
            }
        } catch (error) {
            const isAuthFailed = error.response?.status === 401 || error.response?.status === 403;
            return { isAuthenticated: !isAuthFailed, error };
        }
    },

    // 检查登录状态（校验ID、phone、role）
    isLoggedIn() {
        const userStr = localStorage.getItem('user');
        if (!userStr) return false;

        try {
            const user = JSON.parse(userStr);
            // 必须包含id、phone、role才视为有效
            if (!user.id || !user.phone || !user.role) {
                localStorage.removeItem('user');
                return false;
            }

            // 24小时超时
            const EXPIRE_HOURS = 24;
            const currentTime = new Date().getTime();
            if (!user.loginTime || (currentTime - user.loginTime) > EXPIRE_HOURS * 60 * 60 * 1000) {
                localStorage.removeItem('user');
                return false;
            }

            return true;
        } catch (error) {
            localStorage.removeItem('user');
            return false;
        }
    },

    // 获取当前用户信息
    getCurrentUser() {
        if (!this.isLoggedIn()) return null;
        try {
            return JSON.parse(localStorage.getItem('user')) || null;
        } catch (error) {
            localStorage.removeItem('user');
            return null;
        }
    },

    // 检查角色权限
    hasRole(role) {
        const user = this.getCurrentUser();
        if (!user) return false;
        if (Array.isArray(role)) return role.includes(user.role);
        return user.role === role;
    },

    // 检查登录是否过期
    isLoginExpired(user) {
        if (!user || !user.loginTime || !user.id) return true;
        const EXPIRE_HOURS = 24;
        const currentTime = new Date().getTime();
        return (currentTime - user.loginTime) > EXPIRE_HOURS * 60 * 60 * 1000;
    }
}